package mdata

import (
	"fmt"
	"gitee.com/dennis-mxx/gcode-common/mcore"
	"xorm.io/builder"
)

func BuildFilters(item mcore.Filter) builder.Cond {
	switch item.Type {
	case "like":
		if item.Val != nil {
			return builder.Like{item.Col, fmt.Sprintf("%v", item.Val)}
		}
	case "notLike":
		if item.Val != nil {
			return builder.Not{builder.Like{item.Col, fmt.Sprintf("%v", item.Val)}}
		}
	case "eq":
		if item.Val != nil {
			return builder.Eq{item.Col: item.Val}
		}
	case "notEq":
		if item.Val != nil {
			return builder.Not{builder.Eq{item.Col: item.Val}}
		}
	case "in":
		if item.Vals != nil {
			return builder.In(item.Col, item.Vals...)
		}
	case "notIn":
		if item.Vals != nil {
			return builder.Not{builder.In(item.Col, item.Vals...)}
		}
	case "rightLike":
		if item.Val != nil {
			return builder.Like{item.Col, fmt.Sprintf("%v", item.Val) + "%"}
		}
	case "leftLike":
		if item.Val != nil {
			return builder.Like{item.Col, "%" + fmt.Sprintf("%v", item.Val)}
		}
	case "isNull":
		return builder.Or(builder.IsNull{item.Col}, builder.Eq{item.Col: ""})
	case "notNull":
		return builder.And(builder.NotNull{item.Col}, builder.Neq{item.Col: ""})
	case "between":
		if len(item.Vals) == 2 {
			return builder.Between{Col: item.Col, LessVal: item.Vals[0], MoreVal: item.Vals[1]}
		}
	case "lt":
		if item.Val != nil {
			return builder.Lt{item.Col: item.Val}
		}
	case "lte":
		if item.Val != nil {
			return builder.Lte{item.Col: item.Val}
		}
	case "gt":
		if item.Val != nil {
			return builder.Gt{item.Col: item.Val}
		}
	case "gte":
		if item.Val != nil {
			return builder.Gte{item.Col: item.Val}
		}
	}
	return nil
}

func BuildCommPage(cmd mcore.CmdCommPage) QueryParam {
	var filterCond []builder.Cond
	for i := range cmd.Filters {
		if filter := BuildFilters(cmd.Filters[i]); filter != nil {
			filterCond = append(filterCond, filter)
		}
	}
	cond := builder.And(filterCond...)
	if cmd.Comm.Value != "" {
		commCond := make([]builder.Cond, len(cmd.Comm.Cols))
		for i := range cmd.Comm.Cols {
			col := cmd.Comm.Cols[i]
			commCond[i] = builder.Like{col, cmd.Comm.Value}
		}
		cond = cond.And(builder.Or(commCond...))
	}
	return QueryParam{
		Cond: cond,
		Page: cmd.CmdPage,
		//Cols: cmd.Cols,
	}

}
